/*******************************************************************************
 * Copyright (c) 2010 marvin.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Contributors:
 *     marvin - initial API and implementation
 ******************************************************************************/

package com.marv42.ebt.newnote.scanning;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import com.marv42.ebt.newnote.R;

import android.content.Context;
import android.net.ParseException;
import android.net.Uri;



public class PictureUploader
{
   private static final String SHORT_TERM_STORAGE_HOST = "http://ws.webservius.com/sts/v1/20mb/15m";



   public static String
   upload(final Uri uri, final Context context)
   {
      HttpClient httpClient = new DefaultHttpClient();
      HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);

      HttpPost request = new HttpPost(SHORT_TERM_STORAGE_HOST + "?wsvKey=" +
                                      Keys.WSV_SHORT_TERM_STORAGE);
      // TODO Do this with an entity?

      String result = "Error";
      try
      {
         request.setEntity(new FileEntity(new File(new URI(uri.toString())), "image/jpeg"));
         result = EntityUtils.toString(httpClient.execute(request).getEntity(), "UTF-8");
      }
      catch (URISyntaxException e)
      {
         return "Error: " + e.getMessage();
      }
      catch (ClientProtocolException e)
      {
         return "Error: " + e.getMessage();
      }
      catch (IOException e)
      {
         if (e.getMessage().contains("unreachable"))
            return "Error: " + context.getString(R.string.error_no_connection);
         return "Error: " + e.getMessage();
      }
      catch (ParseException e)
      {
         return "Error: " + e.getMessage();
      }

      return result;
   }
}
